package com.hhsj.androidserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class HttpHandler implements Runnable {


    public static final int CODE_OK = 200;
    private static final int bufferSize = 1024;
    private final SelectionKey key;
    private int CODE = 200;


    public HttpHandler(SelectionKey key) {
        this.key = key;
    }


    @Override
    public void run() {
        try {
            long start = System.currentTimeMillis();

            // 接收到连接请求时
            if (key.isAcceptable()) {
                try {
                    handleAccept();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if (key.isReadable() && key.isWritable())   //可读可写
            {
                try {
                    HttpServletRequest request = new HttpServletRequest(key);                //封装Request
                    HttpServletResponse response = new HttpServletResponse(key);             //封装Response
                    HttpServlet servlet = WebApp.getInstance().getServlet(request.getUrl());               //通过映射地址获取具体的servlet
                    if (servlet == null) {
                        this.CODE = 404;
                    } else {
                        try {
                            servlet.service(request, response);
                        } catch (Exception e) {
                            e.printStackTrace();
                            this.CODE = 500;
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw, true);
                            pw.flush();
                            sw.flush();
                            response.println(sw.toString());
                        }
                    }
                    response.pushToClient(this.CODE);
                    System.out.println("接口耗时: " + (System.currentTimeMillis() - start) + " ms");
                    request.close();
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception E) {
            E.printStackTrace();
        }

    }


    /**
     * 接收连接处理
     *
     * @throws IOException
     */
    public void handleAccept() throws IOException {
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
        if (null != clientChannel) {
            clientChannel.configureBlocking(false);     //线程不阻塞
            clientChannel.register(key.selector(), SelectionKey.OP_READ | SelectionKey.OP_WRITE, ByteBuffer.allocate(bufferSize));       //注册读写
        }

    }
}